// const app = getApp();
import dxRequest from "../network/index"

// 获取openid和session_key
export function getUserInfoo() {
  wx.login({
    success(res) {
      if (res.code) {
        dxRequest('post', '/access/login', {
          code: res.code
        }).then(res => {
          if (res.statusCode == 201) {
            // 把openid和session_key存起来
            updateUserInfo(res.data.info)
            // 路由跳转
            wx.switchTab({
              url: '/pages/index/index',
            })
            // 弹窗提示
            wx.showToast({
              title: '登录成功',
              duration: 1000,
              icon: 'success',
              mask: true
            })
          } else {
            wx.showToast({
              title: '加载失败',
              icon: 'error',
              mask: true
            })
          }
        })
          .catch(error => {
            wx.showToast({
              title: '加载失败',
              duration: 2000,
              icon: 'error',
              mask: true
            })
            console.log(
              '登录接口请求失败',
              error
            )
          })
      }
    }
  })
}

export function updateUserInfo(data) {
  wx.setStorage({
    key: "session_key",
    data: data.session_key
  })
  wx.setStorage({
    key: "openid",
    data: data.openid
  })

  getApp().globalData.userInfo.openid = data.openid
}

export function sessionKeyValidityCheck() {
  wx.checkSession({
    success() {
      wx.getStorage({
        key: 'openid',
        success(res) {
          // console.log(res.data)
          getApp().globalData.userInfo.openid = res.data
        }
      })
      
      wx.switchTab({
        url: '/pages/index/index',
      })
    },
    fail() {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
  })
}